<template>
  <div class="app-container">
    <!-- 弹窗 -->
    <el-dialog title="提示" :visible.sync="dialogVisible" width="50%" :before-close="handleClose">
      <audio ref="audio" src="" controls></audio>
      <p id="record_audio">识别文字中请稍后</p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>


    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="编号" prop="id">
        <el-input v-model="queryParams.id" placeholder="请输入编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="用户号" prop="userid">
        <el-input v-model="queryParams.userid" placeholder="请输入用户号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="题号" prop="questionnumber">
        <el-input v-model="queryParams.questionnumber" placeholder="请输入题号" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="天数" prop="daynumber">
        <el-input v-model="queryParams.daynumber" placeholder="请输入天数" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="关卡" prop="stage">
        <el-input v-model="queryParams.stage" placeholder="请输入关卡" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="创建时间" prop="creationtime">
        <el-date-picker clearable v-model="queryParams.creationtime" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['lakk:UserProgress:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['lakk:UserProgress:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['lakk:UserProgress:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['lakk:UserProgress:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="UserProgressList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="用户号" align="center" prop="userid" />
      <el-table-column label="题号" align="center" prop="questionnumber" />
      <el-table-column label="天数" align="center" prop="daynumber" />
      <el-table-column label="关卡" align="center" prop="stage" />
      <el-table-column label="题面快照" align="center" prop="questiontextsnapshot" />
      <el-table-column label="用户作答" align="center" prop="useranswer" />
      <el-table-column label="获得奖励" align="center" prop="rewardobtained" />
      <el-table-column label="创建时间" align="center" prop="creationtime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.creationtime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="故事题用户录音文件" align="center" prop="userrecordingfile" />
      <el-table-column label="故事题用户语音转文字" align="center" prop="uservoicetotext" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['lakk:UserProgress:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['lakk:UserProgress:remove']">删除</el-button>
          <el-button v-if="scope.row.userrecordingfile && scope.row.userrecordingfile.length > 20" size="mini"
            type="text" icon="el-icon-video-play" @click="playMusic(scope.row)">播放</el-button>
          <el-button v-if="scope.row.userrecordingfile && scope.row.userrecordingfile.length > 20" size="mini"
            type="text" icon="el-icon-download" @click="downloadit(scope.row)">下载</el-button>
          <el-button v-if="scope.row.userrecordingfile && scope.row.userrecordingfile.length > 20" size="mini"
            type="text" icon="el-icon-magic-stick" @click="orgniz(scope.row)">识别</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改用户进度对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户号" prop="userid">
          <el-input v-model="form.userid" placeholder="请输入用户号" />
        </el-form-item>
        <el-form-item label="题号" prop="questionnumber">
          <el-input v-model="form.questionnumber" placeholder="请输入题号" />
        </el-form-item>
        <el-form-item label="天数" prop="daynumber">
          <el-input v-model="form.daynumber" placeholder="请输入天数" />
        </el-form-item>
        <el-form-item label="关卡" prop="stage">
          <el-input v-model="form.stage" placeholder="请输入关卡" />
        </el-form-item>
        <el-form-item label="题面快照" prop="questiontextsnapshot">
          <el-input v-model="form.questiontextsnapshot" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="用户作答" prop="useranswer">
          <el-input v-model="form.useranswer" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="获得奖励" prop="rewardobtained">
          <el-input v-model="form.rewardobtained" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="创建时间" prop="creationtime">
          <el-date-picker clearable v-model="form.creationtime" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择创建时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="故事题用户录音文件">
          <editor v-model="form.userrecordingfile" :min-height="192" />
        </el-form-item>
        <el-form-item label="故事题用户语音转文字" prop="uservoicetotext">
          <el-input v-model="form.uservoicetotext" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listUserProgress, getUserProgress, delUserProgress, addUserProgress, updateUserProgress } from "@/api/lakk/UserProgress";
import axios from 'axios';
export default {
  name: "UserProgress",
  data() {
    return {
      dialogVisible: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户进度表格数据
      UserProgressList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        id: null,
        questionnumber: null,
        daynumber: null,
        stage: null,
        questiontextsnapshot: null,
        useranswer: null,
        rewardobtained: null,
        creationtime: null,
        userrecordingfile: null,
        uservoicetotext: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询用户进度列表 */
    getList() {
      this.loading = true;
      listUserProgress(this.queryParams).then(response => {
        var result = response;
        // 遍历rows数组，将localhost字段转换为47.113.227.126
        result.rows.forEach(item => {
          if (item.userrecordingfile) {
            item.userrecordingfile = item.userrecordingfile.replace(/localhost/g, '47.113.227.126');
            console.log(item.userrecordingfile);
          }
        });
        this.UserProgressList = result.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userid: null,
        questionnumber: null,
        daynumber: null,
        stage: null,
        questiontextsnapshot: null,
        useranswer: null,
        rewardobtained: null,
        creationtime: null,
        userrecordingfile: null,
        uservoicetotext: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加用户进度";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getUserProgress(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改用户进度";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateUserProgress(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addUserProgress(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除用户进度编号为"' + ids + '"的数据项？').then(function () {
        return delUserProgress(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('lakk/UserProgress/export', {
        ...this.queryParams
      }, `UserProgress_${new Date().getTime()}.xlsx`)
    },
    playMusic(row) {
      console.log(row.userrecordingfile);
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.audio.src = row.userrecordingfile;
        // this.$refs.audio.play();
      });

      // 下载音频文件
      axios.get(row.userrecordingfile, {
        responseType: 'blob'
      }).then(res => {
        // const url = window.URL.createObjectURL(new Blob([res.data]));
        // const link = document.createElement('a');
        // link.href = url;
        // link.setAttribute('download', 'audio.mp3'); // 你可以设置任何你想要的文件名
        // document.body.appendChild(link);
        // link.click();
        // link.remove();

        // 上传音频文件
        const formData = new FormData();
        formData.append('audio', res.data, 'audio.mp3'); // 使用与下载文件名相同的名字
        axios.post('http://47.113.227.126:1002/upload', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        }).then(uploadRes => {
          console.log(uploadRes.data);
          record_audio.innerHTML = uploadRes.data;
          var form_temp = {
            id: row.id,
            uservoicetotext: uploadRes.data
          };
          updateUserProgress(form_temp).then(response => {

          });
        }).catch(uploadErr => {
          console.error(uploadErr);
        });
      }).catch(downloadErr => {
        console.error(downloadErr);
      });
    },
    handleClose(done) {
      console.log('关闭');
      this.$refs.audio.pause();
      record_audio.innerHTML = '识别文字中请稍后';
      done();
    },
    orgniz(row) {
      // 下载音频文件
      axios.get(row.userrecordingfile, {
        responseType: 'blob'
      }).then(res => {
        // const url = window.URL.createObjectURL(new Blob([res.data]));
        // const link = document.createElement('a');
        // link.href = url;
        // link.setAttribute('download', 'audio.mp3'); // 你可以设置任何你想要的文件名
        // document.body.appendChild(link);
        // link.click();
        // link.remove();

        // 上传音频文件
        const formData = new FormData();
        formData.append('audio', res.data, 'audio.mp3'); // 使用与下载文件名相同的名字
        axios.post('http://47.113.227.126:1002/upload', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        }).then(uploadRes => {
          console.log(uploadRes.data);
          var form_temp = {
            id: row.id,
            uservoicetotext: uploadRes.data
          };
          updateUserProgress(form_temp).then(response => {
            // 提示识别成功
            this.$message({
              message: '识别成功' + uploadRes.data,
              type: 'success'
            });
          });
        }).catch(uploadErr => {
          console.error(uploadErr);
          this.$message({
            message: '识别失败：' + uploadErr,
            type: 'danger'
          });
        });
      }).catch(downloadErr => {
        console.error(downloadErr);
        this.$message({
          message: '识别失败：' + downloadErr,
          type: 'danger'
        });
      });
    },
    downloadit(row) {
      // 下载音频文件
      axios.get(row.userrecordingfile, {
        responseType: 'blob'
      }).then(res => {
        const url = window.URL.createObjectURL(new Blob([res.data]));
        const link = document.createElement('a');
        link.href = url;
        let filename = row.userrecordingfile.split("/").pop();
        link.setAttribute('download', filename); // 你可以设置任何你想要的文件名
        document.body.appendChild(link);
        link.click();
        link.remove();
      }).catch(downloadErr => {
        console.error(downloadErr);
      });
    }
  }

};
</script>
